package dao;

import entity.Order;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import utils.DBUtil;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class OrderDao {
    QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
    BeanListHandler<Order> blh = new BeanListHandler<>(
            Order.class, new BasicRowProcessor(new GenerousBeanProcessor()));

    /**
     * 添加订单
     * @return 影响数据行数
     */
    public int add(Order order){
        String sql = "insert into `order` values (?,?,?,?,?)";
        try {
            return queryRunner.update(sql, order.getUserName(), order.getProductName(),
                    order.getType(), order.getPrice(), order.getStatus());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询订单(多表联查)
     */
    public List<Map<String, Object>> query(String sql, Object... params){
        //创建结果集处理器
        MapListHandler mlh = new MapListHandler();
        try {
            return queryRunner.query(sql, mlh, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 更新订单
     */
    public int update(String sql, Object... params){
        try {
            return queryRunner.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
